<template>
  <!-- 新增个人信息 -->
  <div class="add-my-info">
    <div class="main">
      <el-form :model="submitQuery" :inline="true" :rules="rules" ref="fromRef">
        <el-form-item label="昵称" prop="name">
          <el-input placeholder="请输入昵称" v-model="submitQuery.name"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            v-model:file-list="fileList"
            list-type="picture"
            :headers="{ token: token }"
            :action="serverUploadImg"
            :on-success="handleSuccess"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :limit="1"
          >
            <el-button type="primary" size="small">选择头像</el-button></el-upload
          >
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="submitMyInfo">提交</el-button>
        </el-form-item>
        <el-form-item class="input-desc" label="个人简介" prop="desc" style="display: flex">
          <el-input
            type="textarea"
            placeholder="请输入..."
            v-model="submitQuery.desc"
            maxlength="200"
            show-word-limit
            :rows="3"
            :autosize="{ minRows: 3, maxRows: 5 }"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <TextEditor v-model="submitQuery.story" />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { addMyInfoService, getMyInfoByIdService, updateMyInfoService } from '@/api/MyInfo'
import TextEditor from '@/components/TextEditor.vue'
import { serverStore } from '@/stores/server'
import { decryptData } from '@/utils/CryptoJSUtil'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'

const { serverUploadImg } = serverStore()
const router = useRouter()
const route = useRoute()

const id = route.params.id

const submitQuery = ref({
  id: id,
  name: '',
  headerUrl: '',
  desc: '',
  story: '',
})
const fileList = ref([])

const fromRef = ref()
/**
 * 表单验证
 */
const rules = {
  name: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
  desc: [{ required: true, message: '简介不能为空', trigger: 'blur' }],
}
// 上传成功的回调函数
const handleSuccess = () => {
  ElMessage.success('上传成功')
  if (successImgArr.value[0].response && typeof successImgArr.value[0].response === 'string') {
    try {
      const decrypted = decryptData(successImgArr.value[0].response)
      const url = JSON.parse(decrypted).msg
      submitQuery.value.headerUrl = url
    } catch (err) {
      console.error('解密响应失败:', err)
    }
  }
}
const token = localStorage.getItem('token')
// 点击上传列表图片
const handlePreview = (file) => {
  console.log('列表', file)
}
// 移除出列表图片
const handleRemove = () => {
  ElMessage.success('移除图片')
  console.log('移除图片')
}
const handleError = () => {
  ElMessage.error('图片上传失败')
}
const handleExceed = () => {
  ElMessage.warning('超出上传图片上限')
}

/**
 * 提交
 */
const submitMyInfo = () => {
  fromRef.value.validate((valid) => {
    if (valid) {
      // 通过表单验证
      if (submitQuery.value.story === '<p><br></p>') {
        ElMessage.error('内容不能为空')
        return false
      } else {
        if (id === '-1') {
          addMyInfoService(submitQuery.value).then(() => {
            submitQuery.value = {
              name: '',
              headerUrl: '',
              desc: '',
              story: '',
            }
            router.go(-1)
          })
        } else {
          updateMyInfoService(submitQuery.value).then(() => {
            router.go(-1)
            console.log(submitQuery.value)
          })
        }
      }
    }
  })
}

/**
 * 获取个人信息详细信息
 * @param id
 */
const getMyInfo = async (id) => {
  if (id !== '-1') {
    const { data } = await getMyInfoByIdService(id)
    submitQuery.value.name = data.name
    submitQuery.value.headerUrl = data.headerUrl
    fileList.value.push({
      name: data.headerUrl,
      url: data.headerUrl,
    })
    submitQuery.value.desc = data.desc
    submitQuery.value.story = data.story
  } else {
    console.log('当前是新增')
  }
}

onMounted(() => {
  getMyInfo(id)
})
</script>

<style lang="scss" scoped>
* {
  border: none !important;
}

.add-my-info {
  padding: 15px;
  background-color: #f3f4f5;

  .main {
    min-height: 100vh;
    padding: 20px;
    background-color: #fff;
    border-radius: 7px;

    :deep(.el-textarea) {
      width: 30vw;
    }

    .input-desc {
      :deep(textarea) {
        position: relative;
        resize: none;
      }
    }
  }
}
</style>